<template>
  <base-breadcrumb
    class="UpdatePartyActivity-container fixed-container"
    :title="breadcrumbTitle"
    :breadcrumb="!isAudit"
  >
    <a-spin :spinning="!!loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="formInfo"
          :form-list="formItemList"
          @selectNode="handleSelectOrg"
          @getOption="handleGetOption"
        >
          <template v-slot:sectionTitle>
            <title-name title="活动信息" />
          </template>
          <template v-slot:fileIds>
            <l-table
              :disabled="isDisabled"
              :upload-arrys.sync="formInfo.fileIds"
              business-code="PARTY02"
              upload-type="image"
              :edit-model="2"
            />
          </template>
        </custom-form>
        <title-name title="相关附件" />
        <UploadTableNew
          ref="uploadTable"
          :disabled="isDisabled"
          business-code="PARTY03"
          :mode="pageType"
          :request-fn="getFileList"
        />
      </a-card>
      <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
        <!-- .如果是状态不为“未提交”时，编辑页面就没有保存草稿 -->
        <a-button
          v-if="pageType === 'add' || (pageType !== 'add' && $route.query.status == '0' && pageType !== 'look')"
          class="ml12"
          type="primary"
          :loading="loadingState.DRAFT"
          @click="handleSubmit('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import {
  getActivityDetail,
  getACtivityFiles,
  addActivity,
  editActivity
} from '@/api/partyMasses/partyManage/partyActivity.js'
import Selector from '@/components/Select/Selector.vue'
import PartyTreeSelect from '../../componments/partyTreeSelect.vue'
import Vue from 'vue'
import Moment from 'moment'
import { PARTY_TYPE_MAP } from '@/config/businessConfig.js'
import { async } from 'regenerator-runtime'

export default {
  name:'a'+ Date.now(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activityDesc: 'activity', // 党群活动类型：'activity' | 'survey'
      isHiddenOrgSelect: false,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false
      },
      formInfo: {},
       //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 当前的活动信息是否为党群活动类型
    isActivityType() {
      return this.activityDesc === 'activity'
    },
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增党群活动',
        edit: '编辑党群活动',
        look: '组织党群活动'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '活动名称',
          keyName: 'activityName',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '举办组织',
          keyName: 'partyOrgId',
          viewName: 'partyOrgName',
          type: PartyTreeSelect,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          hidden: this.isHiddenOrgSelect,
          attrs: {
            returnInitNode: true,
            orgStatus: 1
          }
        },
        {
          label: '其他参与单位',
          keyName: 'participateUnit',
          type: 'BaseInput',
          disabled: this.isDisabled
        },
        {
          label: '活动日期',
          keyName: 'activityTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          label: '活动类型',
          keyName: 'activityTypeId',
          viewName: 'activityTypeName',
          type: Selector,
          disabled: this.isDisabled || this.pageType !== 'add' && this.$route.query.status != '0', // 编辑页面并处于未提交状态时不可修改
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            urlType: 'union',
            selectType: 24
          }
        },
        {
          label: '是否推为新闻报道',
          keyName: 'ifPushNews',
          type: 'a-select',
          disabled: this.isDisabled || this.pageType !== 'add' && this.$route.query.status != '0', // 编辑页面并处于未提交状态时不可修改
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          data: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          label: '组织生活级别',
          keyName: 'lifeLevel',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'sectionTitle',
          span: 24
        },
        {
          label: '事件级别',
          keyName: 'eventLevelId',
          viewName: 'eventLevelName',
          type: Selector,
          disabled: this.isDisabled,
          hidden: !this.isActivityType,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            urlType: 'union',
            selectType: 25
          }
        },
        {
          label: '负责人',
          keyName: 'principal',
          type: 'BaseInput',
          disabled: this.isDisabled,
          hidden: !this.isActivityType,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '参加人',
          keyName: 'intervenor',
          type: 'BaseInput',
          disabled: this.isDisabled,
          hidden: !this.isActivityType,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '活动地点',
          keyName: 'address',
          type: 'BaseInput',
          disabled: this.isDisabled,
          hidden: !this.isActivityType,
          span: 16,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '新闻报道',
          keyName: 'newsReport',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          hidden: !this.isActivityType,
          span: 24,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          attrs: {
            maxLength: 5000
          },
          autoSize: { minRows: 3, maxRows: 30 },
        },
        {
          label: '调研主题',
          keyName: 'researchTopic',
          disabled: this.isDisabled,
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          label: '调研对象',
          keyName: 'researchObject',
          disabled: this.isDisabled,
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          label: '调研人',
          keyName: 'researchPeople',
          disabled: this.isDisabled,
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          label: '调研地点',
          keyName: 'researchAddress',
          disabled: this.isDisabled,
          type: 'BaseInput',
          span: 16,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          label: '调研内容',
          keyName: 'researchContent',
          disabled: this.isDisabled,
          type: 'BaseTextarea',
          span: 24,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          label: '工作建议',
          keyName: 'workProposal',
          disabled: this.isDisabled,
          type: 'BaseTextarea',
          span: 24,
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          needActivityType: 'survey',
          hidden: this.isActivityType,
        },
        {
          slot: true,
          keyName: 'fileIds',
          label: '附图',
          isRequired: true
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          if(!item.needActivityType || item.needActivityType && item.needActivityType === this.activityDesc) {
            map[item.keyName] = item.rules
          }
        }
      })
      return map
    }
  },
 async created() {
    this.initPage()
    this.getActivityDetailReq()
      //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('Foundation_of_the_Party_push_as_news')
    console.log( this.processConfig,' this.processConfig ')
  },
  methods: {
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.formInfo = {
        ...this.formInfo,
        creatorName: userInfo.name,
        activityTime: curDate,
        createTime: curDate,
        ifPushNews: 0 // 默认为否
      }
    },
    handleGetOption(key, val) {
      if (key === 'activityTypeId' && val) {
        const { code } = val
        // 0: 党群活动       1：党群调研
        this.activityDesc = code === '1' ? 'survey' : 'activity'
      }
    },
    handleSelectOrg(key, data) {
      const { orgType, id } = data
      this.formInfo = {
        ...this.formInfo,
        partyOrgId: id,
        lifeLevel: PARTY_TYPE_MAP[orgType]
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('partyOrgId')
      })
    },
    async getActivityDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getActivityDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          fileIds: res.data.fileInfoList || []
        }
        this.isHiddenOrgSelect = true
        this.$nextTick(() => {
          this.isHiddenOrgSelect = false
        })
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    getFileList(params) {
      if (!this.$route.query.id) {
        return Promise.resolve()
      }
      return getACtivityFiles({ ...params, query: { partyActivityId: this.$route.query.id, type: 2 } })
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
       this.setProcessConfig = null;
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.formItemList.forEach((item) => {
            if (item.isRequired && actionName === 'SUBMITTED' && !this.formInfo[item.keyName]?.length) {
              this.$message.warning(`请上传${item.label}`)
              throw new Error('break')
            }
          })
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
       try{
          this.submitApprovalConfirm(actionName =='SUBMITTED'?this.processConfig:6, async(flag)=>{
            if(!flag) {
                  this.loading[actionName] = false
                  return
              }
            this.loadingState[actionName] = true
            const { addIds, delIds } = this.$refs.uploadTable.getChangedFileIds()
            const params = {
              ...this.formInfo,
              fileIds: (this.formInfo.fileIds && this.formInfo.fileIds.map((item) => item.commonId)) || [],
              status: actionName === 'SUBMITTED' ? 1 : 0,
              addRelatedFileIds: addIds,
              removeRelatedFileIds: delIds
            }
            const fn = this.pageType === 'add' ? addActivity : editActivity
          let res = await fn(params)
            this.loadingState[actionName] = false
            this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
            this.$refs.uploadTable.batchDeleteFile() // 删除文件
            if(actionName=== 'SUBMITTED'){
              // this.$multiTab.close() 
              //提交时，返回id
              console.log(res,'res')
              if(res.data.status*1===2 && res.data?.isApprovalButton*1===1){
                this.businessId = res.data.id + '';
                this.setProcessConfig = this.processConfig;
              }else{
                this.$multiTab.close() 
              }

            }else{
              this.$multiTab.close() 
            }
          })

      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    }
  }
}
</script>

<style lang="less" scoped>
.file-tips {
  color: #999999;
  padding-left: 50px;
}
</style>
